package xyz.labmem.main.modular.common.service

import com.alibaba.excel.EasyExcel
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.fasterxml.jackson.annotation.JsonFormat
import org.springframework.web.bind.annotation.RequestMapping
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.main.modular.app.zzdy.entity.Zyjsrycjb
import java.net.URLEncoder
import javax.servlet.http.HttpServletResponse


/**
 * @Author lty
 * @Date 2022/1/24 15:00
 */
fun BaseController.appDownloadTemplate(controller: Any, response: HttpServletResponse, entity: Any) {
    response.contentType = "application/vnd.ms-excel"
    response.characterEncoding = "utf-8"
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    val fileName: String = URLEncoder.encode("${getTag(controller)}-数据模板", "UTF-8")
    response.setHeader("Content-disposition", "attachment;filename=$fileName.xlsx")
    EasyExcel.write(response.outputStream, entity::class.java)
        .sheet("模板")
        .doWrite(arrayListOf(entity))
}

fun <T> BaseController.appDownloadTemplate(controller: Any, response: HttpServletResponse, entity: Any, mapper : BaseMapper<T>) {
    val userPage: Page<T> = Page(1, 1)
    var pages = mapper.selectPage(userPage, QueryWrapper())
    var aa : Any
    if(pages.records.size>0){
        aa = pages.records[0]!!
    }else{
        aa = entity
    }
    response.contentType = "application/vnd.ms-excel"
    response.characterEncoding = "utf-8"
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    val fileName: String = URLEncoder.encode("${getTag(controller)}-数据模板", "UTF-8")
    response.setHeader("Content-disposition", "attachment;filename=$fileName.xlsx")

    EasyExcel.write(response.outputStream, entity::class.java)
        .sheet("模板")
        .doWrite(arrayListOf(aa))
}


